import { Injectable } from '@nestjs/common';
import { CreateIconListDto } from './dto/create-icon-list.dto';
import { UpdateIconListDto } from './dto/update-icon-list.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { IconList } from './entities/icon-list.entity';
import { IconGroupList } from './entities/iconGroup-list.entity';
import { Repository } from 'typeorm';
import * as path from 'path';
import * as fs from 'fs';
import * as compressing from 'compressing';
import * as AdmZip from 'adm-zip'; //用于读取未解压的zip包
import { deleteFolderRecursive } from '../../util/index';

@Injectable()
export class IconListService {
  constructor(
    @InjectRepository(IconList)
    private readonly iconRepository: Repository<IconList>,

    @InjectRepository(IconGroupList)
    private readonly iconGroupRepository: Repository<IconGroupList>,
  ) {}

  upload(file) {
    file.url = `http://${process.env.localURL}:3000/${file.path}`;
    return file;
  }

  async create(createIconListDto: CreateIconListDto) {
    try {
      console.log(createIconListDto);
      let iconGroup = await this.iconGroupRepository.findOne({
        where: { name: createIconListDto.name },
      });
      if (!iconGroup) {
        iconGroup = this.iconGroupRepository.create({
          name: createIconListDto.name,
        });
        await this.iconGroupRepository.save(iconGroup);
      }
      switch (path.extname(createIconListDto.fileInfo.originalname)) {
        case '.svg':
          console.log('我是svg');
          return await this.createSvg(createIconListDto);
        case '.zip':
          console.log('我是zip');
          return await this.createZip(createIconListDto);
        default:
          return '我啥也不知道';
      }
    } catch (err) {
      console.error(err);
    }
  }

  getGroupList() {
    return this.iconGroupRepository.find();
  }

  async getIconList(id: number) {
    const iconGroup = await this.iconGroupRepository.findOne({
      where: { id: id },
      relations: ['iconList'],
    });
    if (iconGroup) {
      return iconGroup.iconList;
    }
    return [];
  }

  // 向数据库中存入单个svg
  async createSvg(createIconListDto: CreateIconListDto) {
    const iconGroup = await this.iconGroupRepository.findOne({
      where: { name: createIconListDto.name },
    });
    const filePath = path.join(__dirname, '../../../', createIconListDto.path);
    const data = fs.readFileSync(filePath, 'utf8');
    const iconList = this.iconRepository.create({
      svgString: data,
      iconName: createIconListDto.fileInfo.originalname,
      iconGroup: iconGroup,
    });
    await this.iconRepository.save(iconList);
    return iconList;
  }

  // 向数据库中存入zip中的svg
  async createZip(createIconListDto: CreateIconListDto) {
    const iconGroup = await this.iconGroupRepository.findOne({
      where: { name: createIconListDto.name },
    });
    const zipFilePath = path.join(
      __dirname,
      '../../../',
      createIconListDto.path,
    );
    const iconDirPath = path.join(zipFilePath, '../');
    // 将压缩包解压到 test 文件夹中
    await compressing.zip.uncompress(zipFilePath, iconDirPath, {
      zipFileNameEncoding: 'gbk',
    });
    // new AdmZip(zipFilePath, 'GBK');
    console.log(`已解压☞${iconDirPath}`);
    const zip = new AdmZip(zipFilePath);
    const zipEntries = zip.getEntries();
    console.log(zipEntries.rawEntryName);
    const res = [];
    let folderName = '';
    // 遍历压缩包中的所有条目（包括文件和文件夹）
    zip.getEntries().forEach((entry) => {
      // 检查是否为目录条目
      if (entry.isDirectory) {
        folderName = entry.entryName.toString('GBK'); // 尝试 GBK 编码
        // 或者尝试 UTF-8 编码
        // let folderName = entry.entryName.toString('utf8');
        console.log(`Folder: ${folderName}`);
      }
    });
    const folderDirPath = path.join(iconDirPath, folderName);
    const filesAndFolders = fs.readdirSync(path.join(folderDirPath));
    for (let i = 0; i < filesAndFolders.length; i++) {
      const fileName = filesAndFolders[i];
      console.log(`Item: ${fileName}`);
      if (path.extname(fileName) === '.svg') {
        const filePath = path.join(folderDirPath, fileName);
        console.log(path.join(folderDirPath, fileName));
        const data = fs.readFileSync(filePath, 'utf8');
        const iconList = this.iconRepository.create({
          svgString: data,
          iconName: path.basename(filePath),
          iconGroup: iconGroup,
        });
        await this.iconRepository.save(iconList);
        res.push(iconList);
      }
    }
    // 删除文件夹及其内容
    await deleteFolderRecursive(iconDirPath);
    // zipEntries.forEach(async (item) => {
    //   if (path.extname(item.entryName) === '.svg') {
    //     const filePath = path.join(
    //       iconDirPath,
    //       item.entryName.toString('utf8'),
    //     );
    //     console.log(item.entryName.toString('utf8'));
    //     const data = fs.readFileSync(filePath, 'utf8');
    //     const iconList = this.iconRepository.create({
    //       svgString: data,
    //       iconName: path.basename(filePath),
    //       iconGroup: iconGroup,
    //     });
    //     await this.iconRepository.save(iconList);
    //     res.push(iconList);
    //   }
    // });
    return res;
  }
  findAll() {
    return `This action returns all iconList`;
  }

  findOne(id: number) {}

  update(id: number, updateIconListDto: UpdateIconListDto) {
    return `This action updates a #${id} iconList`;
  }

  remove(id: number) {
    return `This action removes a #${id} iconList`;
  }
}
